package projetomsn.Client.UI;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Vector;
import java.util.logging.Level;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import projetomsn.Client.ServerInterface.ClientManager;

import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.swing.JFrame;
import projetomsn.Client.DataBase.FriendManager;
import projetomsn.Client.UI.sounds.*;
import projetomsn.Server.ServerInterface;
import projetomsn.Server.ServerSettings;

/**
 * Classe da janela principal do programa
 * @author Greg
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Gerenciador de mensagem
     */
    private ClientManager messageManager; // communicates with server
    /**
     * Recebe mensagens de outro usuário
     */
    private ServerInterface messageListener; // receives incoming messages
    /**
     * Janela para conversação com todos os usuários
     */
    private ChatWithAllFrame chatFrame;//frame used to chat with all users
    /**
     * Armazena o nome do usuário
     */
    private static String userName = "";
    /**
     * Variável que indica se a janela está visível ou não
     */
    private boolean chatIsVisible = false;//set if chat is visible or not
    /**
     * Armazena os frames usados
     */
    private Vector<SingleChatFrame> usedSingleChatFrameVector;
    /**
     * Armazena amigos adicionados
     */
    private Vector<JLabel> friendsLabels;//used to store friends showed
    /**
     * Identificação do usuário
     */
    private int userID;//
    /**
     * Gerenciador de lista de amigos
     */
    private FriendManager friendsListManager;//manipulates database 
    /**
     * Array de lista de amigos
     */
    private ArrayList<String> friendList;//store friends from database
    /**
     * Gerador de log
     */
    private static Logger log = Logger.getLogger(MainFrame.class.getName());
    String language;
    /**
     * Cria internacionalização
     */
    private ResourceBundle myResources; 
            //= ResourceBundle.getBundle("Properties.messages", Locale.getDefault());

    /** 
     * Cria uma nova janela MainFrame 
     */
    public MainFrame(ClientManager manager) throws SQLException {
        Locale.getDefault();
        
        if(Locale.getDefault().toString().equalsIgnoreCase("pt_BR"))
        language = "Properties/messages_pt_BR";
        else if(Locale.getDefault().toString().equalsIgnoreCase("en_US"))
        language = "Properties/messages_en_US";
        
        myResources =
        ResourceBundle.getBundle(language , Locale.getDefault());

        initComponents();

        messageManager = manager; // configura a ClientInterface
        // cria MyMessageListener para receber mensagens
        messageListener = new MyMessageListener();
        chatFrame = new ChatWithAllFrame(manager);
        chatFrame.setVisible(false);
        setTitle(myResources.getString("main.titulo") + chatFrame.getUserName());
        usedSingleChatFrameVector = new Vector<SingleChatFrame>();
        friendsLabels = new Vector<JLabel>();
        disconnectButton.setEnabled(false);
        disconnectMenuItem.setEnabled(false);
        friendsListManager = new FriendManager();
        friendList = new ArrayList<String>();
        updateFriendList();//atualiza a lista de amigos
        setMyStatus("offline");

    }

    /** This method is called header within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        backgroundJPanel = new javax.swing.JPanel();
        goToChatButton = new javax.swing.JButton();
        disconnectButton = new javax.swing.JButton();
        connectButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        friendsListJTextPane = new javax.swing.JTextPane();
        friendButtonPanel = new javax.swing.JPanel();
        addFriendJButton = new javax.swing.JButton();
        deleteFriendJButton = new javax.swing.JButton();
        editFriendJButton = new javax.swing.JButton();
        statusBarJPanel = new javax.swing.JPanel();
        statusJLabel = new javax.swing.JLabel();
        statusPanel = new javax.swing.JPanel();
        myStatusLabel = new javax.swing.JLabel();
        iconStatusLabel = new javax.swing.JLabel();
        mainMenuBar = new javax.swing.JMenuBar();
        serverMenu = new javax.swing.JMenu();
        connectMenuItem = new javax.swing.JMenuItem();
        disconnectMenuItem = new javax.swing.JMenuItem();
        optionMenu = new javax.swing.JMenu();
        soundCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem();
        myStatusMenu = new javax.swing.JMenu();
        onlineMenuItem = new javax.swing.JMenuItem();
        offlineMenuItem = new javax.swing.JMenuItem();
        awayMenuItem = new javax.swing.JMenuItem();
        busyMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        helpFileMenuItem = new javax.swing.JMenuItem();
        tutorialMenuItem = new javax.swing.JMenuItem();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setBounds(new java.awt.Rectangle(0, 0, 300, 532));
        setMinimumSize(new java.awt.Dimension(10, 10));
        setResizable(false);

        backgroundJPanel.setBackground(new java.awt.Color(255, 255, 255));
        backgroundJPanel.setAutoscrolls(true);

        goToChatButton.setBackground(new java.awt.Color(249, 229, 233));
        goToChatButton.setFont(new java.awt.Font("Tahoma", 0, 18));
        goToChatButton.setForeground(new java.awt.Color(181, 1, 1));
        goToChatButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/allChat.png"))); // NOI18N
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Properties/messages"); // NOI18N
        goToChatButton.setToolTipText(bundle.getString("main.button.chatroom")); // NOI18N
        goToChatButton.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(231, 183, 183), 3, true));
        goToChatButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                goToChatButtonMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                goToChatButtonMouseExited(evt);
            }
        });
        goToChatButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goToChatButtonActionPerformed(evt);
            }
        });

        disconnectButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/stop_blue.png"))); // NOI18N
        disconnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectButtonActionPerformed(evt);
            }
        });

        connectButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/play_blue.png"))); // NOI18N
        connectButton.setToolTipText(bundle.getString("main.button.conectar")); // NOI18N
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        friendsListJTextPane.setBackground(new java.awt.Color(235, 241, 255));
        friendsListJTextPane.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Friend's List", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18), new java.awt.Color(0, 51, 102))); // NOI18N
        friendsListJTextPane.setEditable(false);
        jScrollPane1.setViewportView(friendsListJTextPane);

        friendButtonPanel.setBackground(new java.awt.Color(222, 187, 242));
        friendButtonPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        addFriendJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/user_add.png"))); // NOI18N
        addFriendJButton.setToolTipText(bundle.getString("main.button.addFriend")); // NOI18N
        addFriendJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addFriendJButtonActionPerformed(evt);
            }
        });

        deleteFriendJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/user_delete.png"))); // NOI18N

        editFriendJButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/user_edit.png"))); // NOI18N
        editFriendJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editFriendJButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout friendButtonPanelLayout = new javax.swing.GroupLayout(friendButtonPanel);
        friendButtonPanel.setLayout(friendButtonPanelLayout);
        friendButtonPanelLayout.setHorizontalGroup(
            friendButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(friendButtonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(friendButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addFriendJButton)
                    .addComponent(deleteFriendJButton)
                    .addComponent(editFriendJButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        friendButtonPanelLayout.setVerticalGroup(
            friendButtonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(friendButtonPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addFriendJButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteFriendJButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editFriendJButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        statusBarJPanel.setBackground(new java.awt.Color(255, 51, 51));
        statusBarJPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, new java.awt.Color(0, 0, 0)));
        statusBarJPanel.setMinimumSize(new java.awt.Dimension(380, 0));

        statusJLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
        statusJLabel.setText(bundle.getString("main.label.estado.desconectado")); // NOI18N

        javax.swing.GroupLayout statusBarJPanelLayout = new javax.swing.GroupLayout(statusBarJPanel);
        statusBarJPanel.setLayout(statusBarJPanelLayout);
        statusBarJPanelLayout.setHorizontalGroup(
            statusBarJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusBarJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusJLabel)
                .addContainerGap(242, Short.MAX_VALUE))
        );
        statusBarJPanelLayout.setVerticalGroup(
            statusBarJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusJLabel)
        );

        statusPanel.setBackground(new java.awt.Color(229, 229, 233));
        statusPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        myStatusLabel.setFont(new java.awt.Font("Verdana", 1, 18));
        myStatusLabel.setText(bundle.getString("main.label.meuestado")); // NOI18N

        iconStatusLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_offline.png"))); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(myStatusLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(iconStatusLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(myStatusLabel)
                    .addComponent(iconStatusLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout backgroundJPanelLayout = new javax.swing.GroupLayout(backgroundJPanel);
        backgroundJPanel.setLayout(backgroundJPanelLayout);
        backgroundJPanelLayout.setHorizontalGroup(
            backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(backgroundJPanelLayout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(disconnectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, backgroundJPanelLayout.createSequentialGroup()
                            .addGap(28, 28, 28)
                            .addComponent(goToChatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, backgroundJPanelLayout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(friendButtonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(11, 11, 11))
            .addGroup(backgroundJPanelLayout.createSequentialGroup()
                .addComponent(statusBarJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        backgroundJPanelLayout.setVerticalGroup(
            backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(connectButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(disconnectButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(backgroundJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(backgroundJPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, backgroundJPanelLayout.createSequentialGroup()
                        .addGap(112, 112, 112)
                        .addComponent(goToChatButton, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(friendButtonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(44, 44, 44)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(statusBarJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        mainMenuBar.setBackground(new java.awt.Color(157, 157, 212));
        mainMenuBar.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, new java.awt.Color(204, 204, 255)));

        serverMenu.setBackground(new java.awt.Color(157, 157, 212));
        serverMenu.setForeground(new java.awt.Color(255, 255, 255));
        serverMenu.setText(bundle.getString("main.menu.servidor")); // NOI18N
        serverMenu.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14));

        connectMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/conectar.gif"))); // NOI18N
        connectMenuItem.setText(bundle.getString("main.menuitem.conectar")); // NOI18N
        connectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectMenuItemActionPerformed(evt);
            }
        });
        serverMenu.add(connectMenuItem);

        disconnectMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/desconectar.gif"))); // NOI18N
        disconnectMenuItem.setText(bundle.getString("main.menuitem.desconectar")); // NOI18N
        disconnectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectMenuItemActionPerformed(evt);
            }
        });
        serverMenu.add(disconnectMenuItem);

        mainMenuBar.add(serverMenu);

        optionMenu.setBackground(new java.awt.Color(157, 157, 212));
        optionMenu.setForeground(new java.awt.Color(255, 255, 255));
        optionMenu.setText(bundle.getString("main.menu.opcoes")); // NOI18N
        optionMenu.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14));

        soundCheckBoxMenuItem.setSelected(true);
        soundCheckBoxMenuItem.setText(bundle.getString("main.menuitem.habilitar.som")); // NOI18N
        soundCheckBoxMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/sound.png"))); // NOI18N
        soundCheckBoxMenuItem.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                soundCheckBoxMenuItemItemStateChanged(evt);
            }
        });
        soundCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                soundCheckBoxMenuItemActionPerformed(evt);
            }
        });
        optionMenu.add(soundCheckBoxMenuItem);

        myStatusMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/user.png"))); // NOI18N
        myStatusMenu.setText(bundle.getString("main.menuitem.alterar.estado")); // NOI18N

        onlineMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_online.png"))); // NOI18N
        onlineMenuItem.setText(bundle.getString("main.menuitem.conectado")); // NOI18N
        onlineMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onlineMenuItemActionPerformed(evt);
            }
        });
        myStatusMenu.add(onlineMenuItem);

        offlineMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_offline.png"))); // NOI18N
        offlineMenuItem.setText(bundle.getString("main.menuitem.desconectado")); // NOI18N
        offlineMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                offlineMenuItemActionPerformed(evt);
            }
        });
        myStatusMenu.add(offlineMenuItem);

        awayMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_away.png"))); // NOI18N
        awayMenuItem.setText(bundle.getString("main.menuitem.ausente")); // NOI18N
        awayMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                awayMenuItemActionPerformed(evt);
            }
        });
        myStatusMenu.add(awayMenuItem);

        busyMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_occupied.png"))); // NOI18N
        busyMenuItem.setText(bundle.getString("main.menuitem.ocupado")); // NOI18N
        busyMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                busyMenuItemActionPerformed(evt);
            }
        });
        myStatusMenu.add(busyMenuItem);

        optionMenu.add(myStatusMenu);

        mainMenuBar.add(optionMenu);

        helpMenu.setBackground(new java.awt.Color(157, 157, 212));
        helpMenu.setForeground(new java.awt.Color(255, 255, 255));
        helpMenu.setText(bundle.getString("main.menu.ajuda")); // NOI18N
        helpMenu.setFont(new java.awt.Font("Tempus Sans ITC", 0, 14));

        helpFileMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/help.png"))); // NOI18N
        helpFileMenuItem.setText(bundle.getString("main.menuitem.pdf")); // NOI18N
        helpFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpFileMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(helpFileMenuItem);

        tutorialMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/botoes_icones/tutorial.png"))); // NOI18N
        tutorialMenuItem.setText(bundle.getString("main.menuitem.tutorial")); // NOI18N
        tutorialMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tutorialMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(tutorialMenuItem);

        mainMenuBar.add(helpMenu);

        setJMenuBar(mainMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backgroundJPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backgroundJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Evento do botão de desconexão
     * @param evt 
     */
    private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectButtonActionPerformed
        // TODO add your handling code here:
        messageManager.disconnect(messageListener);
        connectButton.setEnabled(true);
        disconnectButton.setEnabled(false);
        statusBarJPanel.setBackground(Color.RED);
        statusJLabel.setText(myResources.getString("main.label.estado.desconectado"));

        try {
            SoundManager.play(Sound.DISCONNECT);
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        setMyStatus("offline");
        
        log.info(myResources.getString("main.log.desconetar"));
}//GEN-LAST:event_disconnectButtonActionPerformed

    /**
     * Evento gerado pelo botão de conexão
     * @param evt 
     */
    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        // TODO add your handling code here:
        messageManager.connect(messageListener);
        connectButton.setEnabled(false);
        disconnectButton.setEnabled(true);
        statusBarJPanel.setBackground(Color.GREEN);
        statusJLabel.setText(myResources.getString("main.label.estado.conectado"));
        try {
            SoundManager.play(Sound.CONNECT);
        } catch (Exception ex) {
        }
        setMyStatus("online");
        
        log.info(myResources.getString("main.log.conectar"));
}//GEN-LAST:event_connectButtonActionPerformed

    /**
     * Evento criado pelo botão de iniciar uma conversa
     * @param evt 
     */
    private void goToChatButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goToChatButtonActionPerformed
        try {
            // TODO add your handling code here:
            chatIsVisible = !chatIsVisible;
            chatFrame.setVisible(chatIsVisible);
            if (userName.equals("")) {
                userName = chatFrame.getUserName();
            }
            SoundManager.play("smb_pipe");
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

}//GEN-LAST:event_goToChatButtonActionPerformed

    /**
     * Evento gerado pelo botão de adicionar amigos
     * @param evt 
     */
    private void addFriendJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFriendJButtonActionPerformed
        // TODO add your handling code here:

        addFriendJButton.setEnabled(false);//
        StringBuilder eMailSearch = new StringBuilder(JOptionPane.showInputDialog(addFriendJButton, myResources.getString("main.email"), myResources.getString("main.search")));

        insertIntoFriendsList(eMailSearch);

        addFriendJButton.setEnabled(true);//

    }//GEN-LAST:event_addFriendJButtonActionPerformed

    /**
     * Evento gerado pelo botão de editar amigos
     * @param evt 
     */
    private void editFriendJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editFriendJButtonActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_editFriendJButtonActionPerformed

    /**
     * Evento gerado pelo botão de tutorial
     * @param evt 
     */
    private void tutorialMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tutorialMenuItemActionPerformed
        // TODO add your handling code here:
        openPDFFile("Tutorial");
}//GEN-LAST:event_tutorialMenuItemActionPerformed

    /**
     * Evento gerado pelo botão de ajuda
     * @param evt 
     */
    private void helpFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpFileMenuItemActionPerformed
        openPDFFile("QuickHelp");
}//GEN-LAST:event_helpFileMenuItemActionPerformed

    /**
     * Evento gerado pelo botão de status ocupado
     * @param evt 
     */
    private void busyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_busyMenuItemActionPerformed
        // TODO add your handling code here:
        setMyStatus("busy");
}//GEN-LAST:event_busyMenuItemActionPerformed

    /**
     * Evento gerado pelo botão de status ausente
     * @param evt 
     */
    private void awayMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_awayMenuItemActionPerformed
        // TODO add your handling code here:
        setMyStatus("away");
}//GEN-LAST:event_awayMenuItemActionPerformed

    /**
     * Evento gerado pelo botão de status offline
     * @param evt 
     */
    private void offlineMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_offlineMenuItemActionPerformed
        // TODO add your handling code here:
        setMyStatus("offline");
}//GEN-LAST:event_offlineMenuItemActionPerformed

    /**
     * Evento gerado pelo botão de status online
     * @param evt 
     */
    private void onlineMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onlineMenuItemActionPerformed
        // TODO add your handling code here:
        setMyStatus("online");
}//GEN-LAST:event_onlineMenuItemActionPerformed

    /**
     * Evento gerado pelo botão que habilita e desabilita o som
     * @param evt 
     */
    private void soundCheckBoxMenuItemItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_soundCheckBoxMenuItemItemStateChanged
        // TODO add your handling code here:
        
        if (soundCheckBoxMenuItem.getState() == true) {
            log.info(myResources.getString("main.log.sound"));
            soundCheckBoxMenuItem.setIcon(
                    new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/botoes_icones/sound.png")));
            soundCheckBoxMenuItem.setText(myResources.getString("main.menuitem.habilitar.som"));

            
        } else {
            log.info(myResources.getString("main.log.no.sound"));
            soundCheckBoxMenuItem.setIcon(
                    new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/botoes_icones/sound_mute.png")));

             
        }


}//GEN-LAST:event_soundCheckBoxMenuItemItemStateChanged

    /**
     * Evento gerado pelo botão que desconecta o usuário do programa
     * @param evt 
     */
    private void disconnectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectMenuItemActionPerformed
        // TODO add your handling code here:
        messageManager.disconnect(messageListener);
        connectMenuItem.setEnabled(true);
        disconnectMenuItem.setEnabled(false);
        connectButton.setEnabled(true);
        disconnectButton.setEnabled(false);
        statusBarJPanel.setBackground(Color.RED);
        statusJLabel.setText(myResources.getString("main.label.estado.conectado"));

        try {
            SoundManager.play(Sound.DISCONNECT);
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        setMyStatus("offline");

        log.info(myResources.getString("main.log.desconetar"));
}//GEN-LAST:event_disconnectMenuItemActionPerformed

    /**
     * Evento gerado pelo botão que conecta o usuário ao programa
     * @param evt 
     */
    private void connectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectMenuItemActionPerformed
        // TODO add your handling code here:
        messageManager.connect(messageListener);
        connectMenuItem.setEnabled(false);
        disconnectMenuItem.setEnabled(true);
        connectButton.setEnabled(false);
        disconnectButton.setEnabled(true);
        statusBarJPanel.setBackground(Color.GREEN);
        statusJLabel.setText(myResources.getString("main.label.estado.desconectado"));

        try {
            SoundManager.play(Sound.CONNECT);
        } catch (Exception ex) {
        }
        setMyStatus("online");

        log.info(myResources.getString("main.log.conectar"));
}//GEN-LAST:event_connectMenuItemActionPerformed

    /**
     * Evento gerado pelo botão que entra na janela de chat
     * @param evt 
     */
    private void goToChatButtonMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goToChatButtonMouseEntered
        // TODO add your handling code here:
        setCursor(Cursor.HAND_CURSOR);
    }//GEN-LAST:event_goToChatButtonMouseEntered

    /**
     * Evento gerado pelo botão que sai da janela de chat
     * @param evt 
     */
    private void goToChatButtonMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goToChatButtonMouseExited
        // TODO add your handling code here:
        setCursor(Cursor.DEFAULT_CURSOR);
    }//GEN-LAST:event_goToChatButtonMouseExited

    /**
     * 
     * @param evt 
     */
    private void soundCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_soundCheckBoxMenuItemActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_soundCheckBoxMenuItemActionPerformed

    /**
     * Metodo configura o status do usuário
     * @param status 
     */
    private void setMyStatus(String status) {
        if (status.equals("online")) {
            iconStatusLabel.setIcon(new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/UserState/qip_online.png")));
            statusPanel.setBackground(new Color(197, 244, 216));
        } else if (status.equals("offline")) {
            iconStatusLabel.setIcon(new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/UserState/qip_offline.png")));
            statusPanel.setBackground(new Color(237, 187, 205));
        } else if (status.equals("away")) {
            iconStatusLabel.setIcon(new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/UserState/qip_away.png")));
            statusPanel.setBackground(new Color(182, 199, 250));
        } else {//busy
            iconStatusLabel.setIcon(new ImageIcon(getClass().getResource(
                    "/projetomsn/Client/pics/UserState/qip_occupied.png")));
            statusPanel.setBackground(new Color(255, 255, 0));
        }

        log.info(myResources.getString("main.log.change.state"));
    }

    /**
     * Metodo pra abrir o arquivo de extensão pdf de ajuda
     * @param fileName 
     */
    private void openPDFFile(String fileName) {
        try {

            File pdfFile = new File(("C:\\MyMessenger\\Help\\" + fileName + ".pdf"));

            if (pdfFile.exists()) {

                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(pdfFile);
                } else {
                    System.out.println(myResources.getString("main.print.desktopError"));

                }

            } else {
                System.out.println(myResources.getString("main.print.file"));

            }

            System.out.println(myResources.getString("main.ok"));


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Metodo usado para atualizar a lista de amigos
     * @throws SQLException 
     */
    private void updateFriendList() throws SQLException {

        friendsListManager.conecta();
        friendList = friendsListManager.getFriends();
        for (int i = 1; i < friendList.size(); i += 2) {
            insertIntoFriendsList(new StringBuilder(friendList.get(i)));
        }
        friendsListManager.desconecta();

          log.info(myResources.getString("main.log.lista.amigos"));
    }

    /**
     * Metodo principal que executa a aplicação
     * @param args the command line arguments
     */
    public static void main(String args[]) throws SQLException {

        ClientManager messageManager = null; // declara ClientInterface

        if (args.length == 0) // conecta ao servidor local
        {
            messageManager = new ClientManager("localhost");
        } else // conecta usando linha de comando arg
        {
            messageManager = new ClientManager(args[ 0]);
        }

        chooseLanguage();

        // cria GUI para ClientManager
        MainFrame mainFrame = new MainFrame(messageManager);


        mainFrame.setVisible(true); // mostra janela

    }
    /**
     * Cria os componentes gerados pelo netbeans
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addFriendJButton;
    private javax.swing.JMenuItem awayMenuItem;
    private javax.swing.JPanel backgroundJPanel;
    private javax.swing.JMenuItem busyMenuItem;
    private javax.swing.JButton connectButton;
    private javax.swing.JMenuItem connectMenuItem;
    private javax.swing.JButton deleteFriendJButton;
    private javax.swing.JButton disconnectButton;
    private javax.swing.JMenuItem disconnectMenuItem;
    private javax.swing.JButton editFriendJButton;
    private javax.swing.JPanel friendButtonPanel;
    private javax.swing.JTextPane friendsListJTextPane;
    private javax.swing.JButton goToChatButton;
    private javax.swing.JMenuItem helpFileMenuItem;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JLabel iconStatusLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuBar mainMenuBar;
    private javax.swing.JLabel myStatusLabel;
    private javax.swing.JMenu myStatusMenu;
    private javax.swing.JMenuItem offlineMenuItem;
    private javax.swing.JMenuItem onlineMenuItem;
    private javax.swing.JMenu optionMenu;
    private javax.swing.JMenu serverMenu;
    private javax.swing.JCheckBoxMenuItem soundCheckBoxMenuItem;
    private javax.swing.JPanel statusBarJPanel;
    private javax.swing.JLabel statusJLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenuItem tutorialMenuItem;
    // End of variables declaration//GEN-END:variables

    /**
     * Metodo usado para inserir amigo na lista
     * @param eMailSearch 
     */
    private void insertIntoFriendsList(StringBuilder eMailSearch) {
        if (eMailSearch.length() > 30) {
            eMailSearch.delete(30, eMailSearch.length() - 1);
        } else {
            String space = "                                  ";
            eMailSearch.append(space, 0, 30 - eMailSearch.length());
        }
        FriendHandler handler = new FriendHandler();
        JLabel l = new JLabel(eMailSearch.substring(0));
        l.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projetomsn/Client/pics/UserState/qip_offline.png")));
        l.setToolTipText(myResources.getString("main.label.user.state"));
        l.addMouseListener(handler);
        friendsLabels.add(l);
        friendsListJTextPane.insertComponent(l);
    }

    /**
     * Classe que trata eventos de mouse
     */
    private class FriendHandler extends MouseAdapter {

        @Override
        // dois cliques com o botão direito do mouse
        public void mouseClicked(java.awt.event.MouseEvent e) {
            String friendName = "";
            if ((e.getClickCount() == 2) && !(e.isMetaDown() || e.isAltDown())) {

                for (int i = 0; i < friendsLabels.size(); i++) {
                    if (e.getSource() == friendsLabels.get(i)) {//pega o rotulo que foi clicado
                        friendName = friendsLabels.get(i).getText();
                        usedSingleChatFrameVector.add(new SingleChatFrame(messageManager, friendName, userName));
                    }
                }
                SingleChatFrame tempFrame;

                for (int i = 0; i < usedSingleChatFrameVector.size(); i++) {
                    tempFrame = usedSingleChatFrameVector.get(i);
                    if (tempFrame.friendName.equals(friendName)) {
                        tempFrame.isVisible = !tempFrame.isVisible;
                        usedSingleChatFrameVector.get(i).setVisible(tempFrame.isVisible);
                    }
                }

            }
        }

        /**
         * Evento gerado pelo mouse sobre a lista de amigos
         * @param e 
         */
        @Override
        public void mouseEntered(java.awt.event.MouseEvent e) {
            setCursor(Cursor.HAND_CURSOR);
        }

        /**
         * Evento gerado pela saida do mouse da lista e amigos
         * @param e 
         */
        @Override
        public void mouseExited(java.awt.event.MouseEvent e) {
            setCursor(Cursor.DEFAULT_CURSOR);
        }
        /*
        public void mousePressed(java.awt.event.MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
        }
        
        public void mouseReleased(java.awt.event.MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
        }
         * 
         */
    }

    /**
     * Trata mensagens recebidas
     */
    private class MyMessageListener implements ServerInterface {
        // quando recebido, mostra novas mensagens na messageArea

        public void messageReceived(String header, String message) {
            // concatena a mensagem usando MessageDisplayer
            SwingUtilities.invokeLater(
                    new MessageDisplayer(header, message));
        } // fim do metodo messageReceived
    } // fim de MyMessageListener inner class

    /**
     * Classe que mostra mensagem
     */
    private class MessageDisplayer implements Runnable {

        private String headerUser; // header do usuario em que recebe a mensagem
        public String messageBody; // corpo da mensagem
        private StringTokenizer msgReceived;

        // construtor MessageDisplayer
        public MessageDisplayer(String header, String body) {
            headerUser = header; // armazena usuario
            messageBody = body; // armazena corpo da mensagem

        }
        // mostra novas mensagens na messageArea

        public void run() {
            // anexa nova mensagem
            String messageReceived = headerUser + ">>> " + messageBody;
            msgReceived = new StringTokenizer(messageReceived, ServerSettings.marca);

            String friend = msgReceived.nextToken();
            String user=msgReceived.nextToken();
            
            chatFrame.getMessage(messageReceived);
            for (int pos = 0; pos < usedSingleChatFrameVector.size(); pos++) {
                usedSingleChatFrameVector.get(pos).getMessage(messageReceived);

                openFriendFrame(friend,user, usedSingleChatFrameVector.get(pos));

            }

        }

        public void openFriendFrame(String friend,String user, SingleChatFrame frame) {
            if(frame.friendName.equals(friend)&&user.equals(MainFrame.userName))
                    frame.setVisible(true);
        }
    }
    public static void chooseLanguage()
    {
    LanguageChooser lc = new LanguageChooser();
    lc.setVisible(true);
    
    while(lc.isVisible()){}
    }
}
